package com.api.apisdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.api.apisdk.utils.SignUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 调用地第三方接口的客户端
 * @author 
 */
public class ApiClient {
    private static final String GATEWAY_HOST = "http://localhost:8098";
    
    private String accessKey;
    
    private String secretKey;
    
    public ApiClient(String accessKey,String secretKey){
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    /**
     * 发送post请求  
     * @param url  请求地地址
     * @param params  请求参数
     * @return
     */
    public String getPostUrl(String url, String params){
        //将params参数生成map集合
        Map<String,Object> paramsMap = JSONUtil.toBean(params,Map.class);
        HttpResponse httpResponse = HttpRequest.post(url)
                .addHeaders(getHeaderMap(params))
                .form(paramsMap)
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }


    /**
     * 发送get请求 
     * @param url
     * @param params
     * @return
     */
    public String getGetUrl(String url, String params){
        HttpResponse httpResponse = HttpRequest.get(url)
                .addHeaders(getHeaderMap(params))
                .form(getMap(params))
                .execute();
        System.out.println(httpResponse.getStatus());
        String result = httpResponse.body();
        System.out.println(result);
        return result;
    }

    private Map<String, Object> getMap(String params){
        Map<String,Object> map = JSONUtil.toBean(params, Map.class);
        return map;
    }
    private Map<String, String> getHeaderMap(String body) {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("accessKey", accessKey);
        // 一定不能直接发送
//        hashMap.put("secretKey", secretKey);
        hashMap.put("nonce", RandomUtil.randomNumbers(4));
        hashMap.put("body", body);
        hashMap.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        hashMap.put("sign", SignUtils.genSign(body, secretKey));
        return hashMap;
    }


}
